package com.voxel.sense.infomsg.module.task.send;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnDismissListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.SnackbarUtils;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.view.EmptyView;
import com.example.com.common.view.dialog.DialogCallBack;
import com.example.com.common.view.dialog.DialogImpl;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.ConditionBean;
import com.voxel.sense.infomsg.module.task.send.firmlist.FirmSelectListActivity;
import com.voxel.sense.infomsg.module.task.send.userlist.UserSeletionListActivity;
import com.voxel.sense.infomsg.view.decoration.ItemDivider;
import com.voxel.sense.infomsg.view.decoration.LinearItemDecoration;
import com.voxel.sense.infomsg.view.titlebar.CommonTitleBar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.api.response.FirmLatestOverDataEntity;
import cyy.example.com.facotry.model.api.response.FirmNameByIdEntity;

//TODO: 修改任务失败情况
public class SendTaskActivity extends BViewActivity<SendTaskContract.Presenter>
        implements SendTaskContract.View, OnOptionsSelectListener {

    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.scroll_view)
    NestedScrollView scroll_view;
    @BindView(R.id.empty_view)
    EmptyView empty_view;
    @BindView(R.id.et_misson_name)
    EditText et_misson_name;
    @BindView(R.id.tv_end_time)
    TextView tv_end_time;
    @BindView(R.id.tv_task_level)
    TextView tv_task_level;
    @BindView(R.id.tv_task_type)
    TextView tv_task_type;
    @BindView(R.id.btn_submit)
    Button btn_submit;
    //输入框的提示文本
    @BindView(R.id.tv_content_count)
    TextView tv_content_count;
    @BindView(R.id.et_advice)
    EditText et_advice;
    //显示已选中的公司
    @BindView(R.id.rv_firm)
    RecyclerView rv_firm;
    //显示已选中的人员
    @BindView(R.id.rv_user)
    RecyclerView rv_user;

    //条件选择器
    private OptionsPickerView mPvCustomOptions;
    //时间选择器
    private TimePickerView mPvTime;
    private List<String> mTypeDatas;
    private List<String> mLevelDatas;
    private TextDatasAdapter mFirmDatasAdapter;
    private UserDatasAdapter mUsertAdapter;
    private static final int mMaxAdviceTextCount = 100;

    private int mCurrentTypeOpt = -1; //记录所选类型的下标
    private int mCurrentLevelOpt = -1;//记录所选等级的下标
    private long mTaskEndTime = -1;//结束时间
    private int mType;
    private String componeName;
    private String mWatchsiteName;
    private String componeId;

    /**
     * @param type 操作类型 100为修改任务 200位发布任务
     */
    public static void show(Context context, int type) {
        Intent intent = new Intent(context, SendTaskActivity.class);
        intent.putExtra(IntentConstants.STRING_TYPE, type);
        context.startActivity(intent);
    }

    public static void show(Context context, int type, FirmLatestOverDataEntity data, String mWatchsiteName) {
        Intent intent = new Intent(context, SendTaskActivity.class);
        intent.putExtra(IntentConstants.STRING_TYPE, type);
        intent.putExtra(IntentConstants.WARM_TASK, data.getCompanyName());
        intent.putExtra(IntentConstants.WARM_POINT, mWatchsiteName);
        intent.putExtra(IntentConstants.WARM_TASK_ID, data.getCompanyId());
        if(data.getSiteData() != null && data.getSiteData().size() > 0 &&data.getSiteData().get(0).getSiteDataList() != null && data.getSiteData().get(0).getSiteDataList().size() > 0) {
            intent.putExtra(IntentConstants.WARM_TASK_OVER, data.getSiteData().get(0).getSiteDataList().get(0).getParamValue());
            intent.putExtra(IntentConstants.WARM_TASK_OVER_VALUE, data.getSiteData().get(0).getSiteDataList().get(0).getParamLimitValue());
            intent.putExtra(IntentConstants.WARM_TASK_OVER_NAME, data.getSiteData().get(0).getSiteDataList().get(0).getParamName());
        }
        context.startActivity(intent);
    }
    /**
     * @param type    操作类型 100为修改任务 200位发布任务
     * @param taskNum 任务编号
     */
    public static void show(Context context, int type, String taskNum, String taskId) {
        if (!TextUtils.isEmpty(taskNum)) {
            Intent intent = new Intent(context, SendTaskActivity.class);
            intent.putExtra(IntentConstants.STRING_TYPE, type);
            intent.putExtra(IntentConstants.TASK_NUMB, taskNum);
            intent.putExtra(IntentConstants.STRING_ID, taskId);
            context.startActivity(intent);
        }
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_send_task;
    }

    @Override
    protected SendTaskPresenter initPresenter() {
        return new SendTaskPresenter(this);
    }


    @Override
    protected void initData() {
        super.initData();
        mType = getIntent().getIntExtra(IntentConstants.STRING_TYPE, SendTaskContract.SEND_TASK);
        componeName = getIntent().getStringExtra(IntentConstants.WARM_TASK);
        mWatchsiteName = getIntent().getStringExtra(IntentConstants.WARM_POINT);
        componeId = getIntent().getStringExtra(IntentConstants.WARM_TASK_ID);
        String mOver = getIntent().getStringExtra(IntentConstants.WARM_TASK_OVER_VALUE);
        String mOverValue = getIntent().getStringExtra(IntentConstants.WARM_TASK_OVER);
        String mOverName = getIntent().getStringExtra(IntentConstants.WARM_TASK_OVER_NAME);
        initCustomOptionPicker();
        buildTimePicker();
        initUserRecycler();
        initFirmRecycler();

        if (SendTaskContract.ALTER_TASK == mType) {
            empty_view.bind(scroll_view);
            String taskNumb = getIntent().getStringExtra(IntentConstants.TASK_NUMB);
            empty_view.triggerLoading();
            mPresenter.doLoadTaskDetailsInfo(taskNumb);
            titlebar.setTitleText("修改任务");
            btn_submit.setText("修改");
        } else {
            btn_submit.setText("派发");
            titlebar.setTitleText("派发任务");
            et_misson_name.setText("跟进解决污染源超标/异常事宜");
            String ov;
            if(TextUtils.isEmpty(mOverValue) || "null".equals(mOverValue)){
                ov = "";
            }else{
                ov = mOverValue;
            }
            String ovKey;
            if(TextUtils.isEmpty(mOver) || "null".equals(mOver)){
              ovKey = "";
            }else{
                ovKey = mOver;
            }
            String name;
            if(TextUtils.isEmpty(componeName) || "null".equals(componeName)){
                name = "";
            }else{
                name = componeName;
            }

            String watchsiteName;
            if(TextUtils.isEmpty(mWatchsiteName) || "null".equals(mWatchsiteName)){
                watchsiteName = "";
            }else{
                watchsiteName = mWatchsiteName;
            }
            String overPackName;
            if(TextUtils.isEmpty(mOverName) || "null".equals(mOverName)){
                overPackName = "";
            }else{
                overPackName = mOverName;
            }
            et_advice.setText("跟进解决超标/异常站点-【"+watchsiteName+"】,超标参数="+overPackName+",超标值="+ov);
            long time = System.currentTimeMillis();
//            Date date = TimeUtils.string2Date(String.valueOf(time), new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()));
            mTaskEndTime = time;
            String format = new SimpleDateFormat("yyyy-MM-dd").format(time);
            tv_end_time.setText(format);
            mPresenter.doGetTaskLevel(1);
            mPresenter.doGetTaskType(1);
            mPresenter.doGetFirmList();
            mPresenter.doGetUserList();
        }
    }

    private void initFirmRecycler() {
        rv_firm.setLayoutManager(new LinearLayoutManager(this));
        mFirmDatasAdapter = new TextDatasAdapter();
        FirmNameByIdEntity firmNameByIdEntity = new FirmNameByIdEntity();
        firmNameByIdEntity.companyId = componeId;
        firmNameByIdEntity.companyName = componeName;

        mFirmDatasAdapter.add(firmNameByIdEntity);
        rv_firm.setAdapter(mFirmDatasAdapter);
        rv_firm.addItemDecoration(new LinearItemDecoration(R.drawable.recycle_divider));
    }

    private void initUserRecycler() {
        rv_user.setLayoutManager(new GridLayoutManager(this, 2));
        mUsertAdapter = new UserDatasAdapter();
        rv_user.setAdapter(mUsertAdapter);
        rv_user.addItemDecoration(new LinearItemDecoration(R.drawable.recycle_divider));
    }

    @Override
    protected void initEven() {
        super.initEven();
        et_advice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tv_content_count.setText((mMaxAdviceTextCount - et_advice.getText().length()) + "");
            }
        });

        empty_view.addRefreshBtnEvent(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String taskNumb = getIntent().getStringExtra(IntentConstants.TASK_NUMB);
                empty_view.triggerLoading();
                mPresenter.doLoadTaskDetailsInfo(taskNumb);
            }
        });


    }


    @OnClick({R.id.tv_task_level, R.id.tv_task_type, R.id.tv_end_time, R.id.tv_firm, R.id.tv_act_user, R.id.btn_submit})
    void OnItemClick(View v) {
        switch (v.getId()) {
            case R.id.tv_task_level:
                //任务等级按钮事件
                if (mLevelDatas == null || mLevelDatas.size() < 1) {
                    mPresenter.doGetTaskLevel(2);
                } else {
                    showOption(mLevelDatas, tv_task_level, "获取任务等级失败列表");
                }
                break;
            case R.id.tv_task_type:
                //任务类型按钮事件
                if (mTypeDatas == null || mTypeDatas.size() < 1) {
                    mPresenter.doGetTaskType(2);
                } else {
                    showOption(mTypeDatas, tv_task_type, "获取类型失败");
                }
                break;
            case R.id.tv_end_time:
                mPvTime.show(tv_end_time);
                break;
            case R.id.tv_firm:
                if (SendTaskContract.ALTER_TASK == mType) {
                    showError("不能修改企业项");
                } else {
                    mPresenter.doGetFirmList();
                }
                break;
            case R.id.tv_act_user: //选择用户
                //任务用户列表事件
                mPresenter.doGetUserList();
                break;
            case R.id.btn_submit:

                List<FirmNameByIdEntity> items = mFirmDatasAdapter.getItems();
                List<String> firms = new ArrayList();
                if(items == null){
                    firms.add(componeId);
                }else {
                    for (FirmNameByIdEntity entity : items) {
                        firms.add(entity.companyId);
                    }
                }
                List<ConditionBean> userBeans = mUsertAdapter.getItems();
                List<String> users = new ArrayList();
                for (ConditionBean bean : userBeans) {
                    users.add(bean.getTipCode());
                }
                String taskName = et_misson_name.getText().toString();
                String Taskcontent = et_advice.getText().toString();
                if (SendTaskContract.ALTER_TASK == mType) {
                    String taskNumb = getIntent().getStringExtra(IntentConstants.TASK_NUMB);
                    String id = getIntent().getStringExtra(IntentConstants.STRING_ID);

                    mPresenter.doAlterTask(taskNumb,id, taskName, mTaskEndTime, mCurrentTypeOpt, mCurrentLevelOpt, Taskcontent, users);
                } else {

                    mPresenter.doSubmitTask(taskName, mTaskEndTime, mCurrentTypeOpt, mCurrentLevelOpt,
                            Taskcontent, firms, users);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onUserList(List list) {

    }

    @Override
    public void onShowFirmList(List datas) {
        FirmSelectListActivity.show(this, (ArrayList<FirmNameByIdEntity>) datas);
    }

    @Override
    public void onShowUserList(List datas) {
        UserSeletionListActivity.show(this, (ArrayList) datas);
    }


    private Map<String, String> taskData;
    @Override
    public void onShowTaskType(List datas, List indexData, Map<String, String> map, int type) {
        mTypeDatas = datas;
        taskData = map;
        if(type == 1){
            String txt = mTypeDatas.get(1);
            tv_task_type.setText(mTypeDatas.get(1));

            mCurrentTypeOpt = Integer.parseInt(map.get(txt));
        }else if(type == 2){
            showOption(datas, tv_task_type, "获取类型失败");
        }

    }

    Map<String, String> mapData;
    @Override
    public void onShowTaskLevel(List datas,List indexData, Map<String, String> map, int type) {
        mLevelDatas = datas;
        mapData = map;
        if(type == 1) {
            tv_task_level.setText(mLevelDatas.get(1));
            String index = (String) indexData.get(1);
            mCurrentLevelOpt = Integer.parseInt(index);
        }
//        mCurrentLevelOpt = mLevelDatas.get(0);
        if(type == 2) {
            showOption(datas, tv_task_level, "获取任务等级失败列表");
        }
    }

    @Override
    public void onRefreshSelectionFirms(List datas) {
        mFirmDatasAdapter.replace(datas);
    }

    @Override
    public void onRefreshSelectionUsers(List datas) {
        mUsertAdapter.replace(datas);
    }

    @Override
    public void onSubmitSuccess() {
        DialogImpl.getInstance().showMessageDialog(this, "", "任务派发成功", new DialogCallBack() {
            @Override
            public void onClick(int what) {
                btn_submit.setEnabled(false);
                finish();
            }
        });
    }

    @Override
    public void onRefreshView(String taskName, String timeEnd, int taskLevelPosition, String levelDesc,
                              int taskTypePosition, String typeDesc, List firm, List user, String taskContent) {
        empty_view.triggerOk();
        et_misson_name.setText(taskName);
        tv_end_time.setText(timeEnd);
        Date date = TimeUtils.string2Date(timeEnd, new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()));
        mTaskEndTime = TimeUtils.getEndOfDay(date).getTime();
        mCurrentLevelOpt = taskLevelPosition;
        tv_task_level.setText(levelDesc);
        mCurrentTypeOpt = taskTypePosition;
        tv_task_type.setText(typeDesc);
        onRefreshSelectionFirms(firm);
        onRefreshSelectionUsers(user);
        et_advice.setText(taskContent);
    }

    @Override
    public void onGetTaskInfoFailure(String msg) {
        empty_view.triggerError(msg);
    }


    //条件选择器初始化，自定义布局
    private void initCustomOptionPicker() {
        mPvCustomOptions = new OptionsPickerBuilder(this, this)
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {//初始化布局
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = v.findViewById(R.id.iv_cancel);
                        //点击完成
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPvCustomOptions.returnData();
                                mPvCustomOptions.dismiss();
                            }
                        });
                        //点击取消
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPvCustomOptions.dismiss();
                            }
                        });
                    }
                })
//                .isDialog(true)
                .build();
    }


    /**
     * 弹出选择器
     */
    private void showOption(List<String> list, final TextView view, String msg) {
        if (list != null && list.size() > 0) {
            view.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.mipmap.ic_drop_selected_icon, 0);
            mPvCustomOptions.setPicker(list);
            mPvCustomOptions.show(view);
            mPvCustomOptions.setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    view.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.mipmap.ic_drop_unselected_icon, 0);
                }
            });

        } else {
            view.setHint(msg);
            ToastUtil.showToastShort(Factory.app(), msg);
        }
    }


    /**
     * 条件选择器回调的方法
     * 返回的分别是三个级别的选中位置
     *
     * @param v 绑定选择器的view
     */
    @Override
    public void onOptionsSelect(int options1, int options2, int options3, View v) {
        switch (v.getId()) {
            case R.id.tv_task_level:
                String levelTxt = mLevelDatas.get(options1);
                tv_task_level.setText(levelTxt);
                String leveCode = mapData.get(levelTxt);
                mCurrentLevelOpt = Integer.parseInt(leveCode);
                break;
            case R.id.tv_task_type:
                String data = mTypeDatas.get(options1);
                tv_task_type.setText(data);
                mCurrentTypeOpt = Integer.parseInt(taskData.get(data));

                break;
            default:
                break;
        }
    }


    /**
     * 创建时间选择器
     */
    private void buildTimePicker() {
        //系统当前时间
        Calendar start = Calendar.getInstance();
        //系统当前时间
        Calendar end = Calendar.getInstance();
        end.set(Calendar.YEAR, start.get(Calendar.YEAR) + 1);
        mPvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                onRefreshTaskTime(date);
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})//分别表示是否显示年，月，日，时，分，秒，默认全部显示
                .setLabel("年", "月", "日", "时", "分", "秒")
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确认")//确认按钮文字
                .setContentTextSize(16)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                .setRangDate(start, end)
//                .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
//                .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
    }

    private void onRefreshTaskTime(Date date) {
        //转换时间格式
        String string = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()));
        tv_end_time.setText(string);
        mTaskEndTime = TimeUtils.getEndOfDay(date).getTime();
    }


    @Override
    public void showSnackBarWarning(String str) {
        super.showSnackBarWarning(str);
        SnackbarUtils.with(scroll_view).setMessage(str).showWarning();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mPresenter.onActivityResult(requestCode, resultCode, data);
    }
}
